package com.ecloud.gardensterminal.server.impl;

import com.ecloud.gardensterminal.common.ResultEnum;
import com.ecloud.gardensterminal.common.exception.ServerException;
import com.ecloud.gardensterminal.constant.DeviceTypeConstant;
import com.ecloud.gardensterminal.domain.GardensDevice;
import com.ecloud.gardensterminal.domain.GardensSleet;
import com.ecloud.gardensterminal.domain.GardensSoil;
import com.ecloud.gardensterminal.domain.GardensWeather;
import com.ecloud.gardensterminal.server.GardensDeviceService;
import com.ecloud.gardensterminal.server.GardensSleetService;
import com.ecloud.gardensterminal.server.GardensSoilService;
import com.ecloud.gardensterminal.server.GardensWeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

/**
 * @author Squbi
 */
@Service
public class GardensAutoServiceImpl implements com.ecloud.gardensterminal.server.GardensAutoService {
    @Autowired
    private GardensDeviceService deviceService;

    @Autowired
    private GardensSoilService soilService;

    @Autowired
    private GardensWeatherService weatherService;

    @Autowired
    private GardensSleetService sleetService;




    @Override
    public boolean checkThreshold(Integer deviceId, String field, Double threshold) {
        GardensDevice gardensDevice = deviceService.selectById(deviceId);
        if (gardensDevice == null) {
            throw new ServerException(ResultEnum.ARGS_ERR, "不存在的设备ID");
        }
        try {
            switch (gardensDevice.getDeviceType()) {
                case DeviceTypeConstant.WEATHER:
                    GardensWeather gardensWeather = weatherService.selectNewly().get(0);
                    return isLowOfThreshold(gardensWeather, field, threshold);
                case DeviceTypeConstant.SOIL:
                    GardensSoil gardensSoil = soilService.selectNewly().get(0);
                    return isLowOfThreshold(gardensSoil, field, threshold);
                case DeviceTypeConstant.SLEET:
                    GardensSleet gardensSleet = sleetService.selectNewly().get(0);
                    return isLowOfThreshold(gardensSleet, field, threshold);
                default:
                    throw new ServerException(ResultEnum.SYS_ERROR, "调用不合法的设备类型");
            }
        } catch (Exception e) {
            throw new ServerException(ResultEnum.SYS_ERROR, e.getMessage());
        }
    }

    private <T> boolean isLowOfThreshold(T a, String field, double threshold) throws NoSuchFieldException, IllegalAccessException {
        Field fieldValue = a.getClass().getDeclaredField(field);
        fieldValue.setAccessible(true);
        Object ao = fieldValue.get(a);
        try {
            return (Integer) ao < threshold;
        } catch (Exception e) {
            return (Double) ao < threshold;
        }
    }

}
